package com.parlons.activities;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.parlons.DatabaseServices;
import com.parlons.R;
import com.parlons.SmackServices;

/**
 * Created by wangyifan on 16/1/1.
 */
public class ChatActivity extends AppCompatActivity {
    public static ListView messageList;
    public static String friendName;
    public static MessageCursorAdapter simpleCursorAdapter;
    public static MessageCursorAdapter messageCursorAdapter;
    public static Handler UIHandler = new Handler(Looper.getMainLooper());

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public class MessageCursorAdapter extends SimpleCursorAdapter {
        private LayoutInflater mLayoutInflater;
        private Context context;
        private int layout;


        private class ViewHolder {
            TextView usernameView;
            TextView contentView;
            ImageView avatarView;

            ViewHolder(View v) {
                usernameView = (TextView) v.findViewById(R.id.message_list_username);
                contentView = (TextView) v.findViewById(R.id.message_list_content);
                avatarView = (ImageView) v.findViewById(R.id.message_list_avatar);
            }
        }

        public MessageCursorAdapter(Context ctx, int layout, Cursor c, String[] from, int[] to, int flag) {
            super(ctx, layout, c, from, to, flag);
            this.context = ctx;
            this.layout = layout;
            mLayoutInflater = LayoutInflater.from(ctx);
        }


        @Override
        public View newView(Context ctx, Cursor cursor, ViewGroup parent) {
            View vView = mLayoutInflater.inflate(layout, parent, false);
            vView.setTag(new ViewHolder(vView));
            // no need to bind data here. you do in later
            return vView;// **EDITED:**need to return the view
        }

        @Override
        public void bindView(View v, Context ctx, Cursor c) {
            int iCol_User = c.getColumnIndex("fromUser");
            int iCol_Content = c.getColumnIndex("content");

            String sUser = c.getString(iCol_User);
            String sContent = c.getString(iCol_Content);
            ViewHolder vh = (ViewHolder) v.getTag();
            if (!sUser.equals(friendName)) {
                /** It's Me */
                vh.usernameView.setText("Me");
                RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(dip2px(getApplicationContext(), 50), dip2px(getApplicationContext(), 50));
                param.addRule(RelativeLayout.ALIGN_PARENT_END);
                param.setMargins(0, dip2px(getApplicationContext(), 10), dip2px(getApplicationContext(), 15), dip2px(getApplicationContext(), 10));
                vh.avatarView.setLayoutParams(param);
                RelativeLayout.LayoutParams paramText = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                paramText.addRule(RelativeLayout.ALIGN_PARENT_END);
                paramText.setMargins(0, dip2px(getApplicationContext(), 10), dip2px(getApplicationContext(), 70), 0);
                vh.usernameView.setLayoutParams(paramText);

                RelativeLayout.LayoutParams paramContent = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                paramContent.addRule(RelativeLayout.ALIGN_PARENT_END);
                paramContent.setMargins(dip2px(getApplicationContext(), 30), dip2px(getApplicationContext(), 30), dip2px(getApplicationContext(), 70), 0);
                vh.contentView.setLayoutParams(paramContent);
                vh.contentView.setBackground(getResources().getDrawable(R.drawable.bubble_my));
            } else {
                /** It's my Friend*/
                vh.usernameView.setText(sUser);
                RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(dip2px(getApplicationContext(), 50), dip2px(getApplicationContext(), 50));
                param.addRule(RelativeLayout.ALIGN_PARENT_START);
                param.setMargins(dip2px(getApplicationContext(), 15), dip2px(getApplicationContext(), 10), 0, dip2px(getApplicationContext(), 10));
                vh.avatarView.setLayoutParams(param);
                RelativeLayout.LayoutParams paramText = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                paramText.addRule(RelativeLayout.ALIGN_PARENT_START);
                paramText.setMargins(dip2px(getApplicationContext(), 70), dip2px(getApplicationContext(), 10), 0, 0);
                vh.usernameView.setLayoutParams(paramText);

                RelativeLayout.LayoutParams paramContent = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                paramContent.addRule(RelativeLayout.ALIGN_PARENT_START);
                paramContent.setMargins(dip2px(getApplicationContext(), 70), dip2px(getApplicationContext(), 30), dip2px(getApplicationContext(), 30), 0);
                vh.contentView.setLayoutParams(paramContent);
                vh.contentView.setBackground(getResources().getDrawable(R.drawable.bubble_friend));

            }

            vh.contentView.setText(sContent);


//            vh.avatarView.setImageBitmap ( mySetImage ( sFileAndPath_Image ) );
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_list);

        TextView message_username = (TextView) findViewById(R.id.message_list_username);

        Intent intent = this.getIntent();
        friendName = intent.getStringExtra("friendName");

        messageList = (ListView) findViewById(R.id.message_list);//得到ListView对象的引用 /*为ListView设置Adapter来绑定数据*/

        DatabaseServices DBService = DatabaseServices.getInstance(this);
        Cursor cursor = DBService.getMessageCursor(SmackServices.getUserName(), friendName, SmackServices.getUserName());


        simpleCursorAdapter = new MessageCursorAdapter(this, R.layout.message_item, cursor, new String[]{"fromUser", "content"}, new int[]{R.id.message_list_username, R.id.message_list_content}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        messageCursorAdapter = new MessageCursorAdapter(this, R.layout.message_item, cursor, new String[]{"fromUser", "content"}, new int[]{R.id.message_list_username, R.id.message_list_content}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        System.out.println("!!!!!!!!!!!!adapter added");

        messageList.setAdapter(simpleCursorAdapter); //为ListView绑定适配器
        if (cursor == null)
            System.out.println("cursor null");
        simpleCursorAdapter.changeCursor(cursor);
        moveToBottom();
        Button sendButton = (Button) findViewById(R.id.send_message_button);
        final EditText sendInput = (EditText) findViewById(R.id.send_message_input);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = sendInput.getText().toString();
                if (content.length() == 0)
                    return;
                sendInput.setText(null);
                SmackServices.sendToFriend(friendName, content);
                System.out.println("message send to: " + friendName + ":" + content);

                DatabaseServices DBService = DatabaseServices.getInstance(getApplicationContext());
                System.out.println("to add msg to db");
                DBService.addMessage(SmackServices.getUserName(), friendName, content, SmackServices.getUserName());
                DBService.addOrUpdateChat(SmackServices.getUserName(), friendName, content);
                System.out.println("Added");
                DBService.close();
                UIHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        while (simpleCursorAdapter == null) {
                            System.out.println("adapter null");
                            try {
                                DatabaseServices DBService = DatabaseServices.getInstance(getApplicationContext());
                                Cursor cursor = DBService.getMessageCursor(SmackServices.getUserName(), friendName, SmackServices.getUserName());
                                simpleCursorAdapter = new MessageCursorAdapter(getApplicationContext(), R.layout.message_item, cursor, new String[]{"fromUser", "content"}, new int[]{R.id.message_list_username, R.id.message_list_content}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
                                Thread.currentThread().sleep(100);
                            } catch (Exception e) {
                                e.printStackTrace();
                                return;
                            }
                        }

                        DatabaseServices DBService = DatabaseServices.getInstance(getApplicationContext());
                        Cursor cursor = DBService.getMessageCursor(SmackServices.getUserName(), friendName, SmackServices.getUserName()); //the order doesn't matter
                        if (cursor == null)
                            System.out.println("cursor null");
                        simpleCursorAdapter.changeCursor(cursor);
                        moveToBottom();


                        if (ChatFragment.simpleCursorAdapter != null) {
                            Cursor cursor2 = DBService.getChatCursor(SmackServices.getUserName()); //the order doesn't matter
                            if (cursor == null)
                                System.out.println("cursor null");
                            if (ChatFragment.simpleCursorAdapter != null) {
                                ChatFragment.simpleCursorAdapter.changeCursor(cursor2);
                            }
                        }
                    }
                });


            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        friendName = null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        friendName = null;
    }

    public static void moveToBottom() {
        messageList.setSelection(ListView.FOCUS_DOWN);
    }


}
